package com.ilide.msgManage.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ilide.msgManage.config.AliSmsConfig;
import com.ilide.msgManage.exception.BusinessException;
import com.ilide.msgManage.model.dto.AliSmsSendDTO;
import com.ilide.msgManage.model.dto.AliSmsSendNoticeDTO;
import com.ilide.msgManage.service.AliSmsService;
import com.ilide.msgManage.utils.WebResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Random;

/**
 * 短信发送接口
 *
 * @author pg
 * @date 2020年3月20日 10:18:22
 */
@Slf4j
@RestController
@Api(value = "短信")
public class SendMessageController {
    @Autowired
    private AliSmsService aliSmsService;

    @Autowired
    private AliSmsConfig aliConfig;

    /**
     * 使用阿里云发送短信
     *
     * @param smsSendDTO
     * @return
     */
    @PostMapping(value = "sendMessage", produces = {"application/json"}, consumes = {"application/json"})
    @ApiOperation(value = "向指定手机号发送随机验证码，返回结果中包含验证码")
    public WebResult sendMessage(@RequestBody AliSmsSendDTO smsSendDTO) {
        try {
            validateParam(ObjectUtil.isNull(smsSendDTO), smsSendDTO.getPhoneNumber());
            //生成验证码
            String verificationCode = getVerificationCode();
            HashMap<String, String> map = new HashMap<>(1);
            map.put("code", verificationCode);
            return aliSmsService.sendSms(smsSendDTO.getPhoneNumber(), aliConfig.getVerificationCode(), map);
        } catch (Exception e) {
            log.error("发送短信失败！", e);
            return WebResult.wrong("发送验证码失败！" + e.getMessage());
        }
    }

    private void validateParam(boolean aNull, String phoneNumber) {
        if (aNull) {
            throw new BusinessException("参数不能为空！");
        }
        if (StrUtil.isBlank(phoneNumber)) {
            throw new BusinessException("参数中手机号码不能为空！");
        }
        if (!Validator.isMobile(phoneNumber)) {
            throw new BusinessException("手机号不正确！");
        }
    }

    /**
     * 生成一个6位的随机数作为验证码，阿里云允许的验证码最长为6位
     *
     * @return
     */
    private String getVerificationCode() throws BusinessException {
        try {
            Random r = new Random();
            StringBuilder code = new StringBuilder();
            int checkCodeLength = 6;
            for (int i = 0; i < checkCodeLength; i++) {
                code.append(r.nextInt(10));
            }
            return code.toString();
        } catch (Exception e) {
            throw new BusinessException("生产验证码失败！");
        }
    }

    @PostMapping(value = "sendBalanceNotice", produces = {"application/json"}, consumes = {"application/json"})
    @ApiOperation(value = "向指定手机号发送余额不足提醒短信")
    public WebResult sendBalanceNotice(@RequestBody AliSmsSendNoticeDTO noticeDTO) {
        try {
            validateParam(ObjectUtil.isNull(noticeDTO), noticeDTO.getPhoneNumber());
            if (StrUtil.isBlank(noticeDTO.getMoney())) {
                throw new BusinessException("不足金额不能为空！");
            }
            if (!Validator.isNumber(noticeDTO.getMoney())) {
                throw new BusinessException("不足金额必须为数值！");
            }
            HashMap<String, String> map = new HashMap<>(1);
            map.put("money", noticeDTO.getMoney());
            return aliSmsService.sendSms(noticeDTO.getPhoneNumber(), aliConfig.getBalanceNotice(), map);
        } catch (Exception e) {
            log.error("发送短信失败！", e);
            return WebResult.wrong("发送验证码失败！" + e.getMessage());
        }
    }

}
